package com.wxd.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wxd.reggie.common.R;
import com.wxd.reggie.entity.Category;
import com.wxd.reggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/category")
@Slf4j
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    /**
     * 添加分类(菜品分类/套餐分类)
     *
     * @param category
     */
    @PostMapping
    public R<String> save(@RequestBody Category category) {
        log.info("添加分类{}", category);
        categoryService.save(category);
        return R.success("添加分类成功");
    }

    /**
     * 查询分类列表
     *
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize) {
        Page<Category> pageInfo = new Page<>(page, pageSize);
        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
        lqw.orderByAsc(Category::getSort);
        categoryService.page(pageInfo, lqw);
        return R.success(pageInfo);
    }

    /**
     * 删除分类
     * 分类下有菜品或套餐 则不允许删除 抛出异常
     *
     * @param id
     */
    @DeleteMapping
    public R<String> delete(Long id) {
        categoryService.delCategory(id);
        return R.success("删除分类成功");
    }

    /**
     * 编辑分类
     *
     * @param category
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody Category category) {
        categoryService.updateById(category);
        return R.success("编辑成功");
    }

    /**
     * 获取菜品分类
     *
     * @param category
     */
    @GetMapping("/list")
    public R<List<Category>> list(Category category) {
        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
        lqw.eq(category.getType() != null, Category::getType, category.getType());
        lqw.orderByAsc(Category::getSort).orderByAsc(Category::getUpdateTime);
        List<Category> list = categoryService.list(lqw);
        return R.success(list);
    }
}
